﻿using System.Reflection;
using System.Runtime.Loader;
using LDM.Framework.Application;
using LDM.Framework.WebApiClientCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyModel;
using WebApiClientCore;
using WebApiClientCore.Serialization.JsonConverters;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// 添加 HttpApi 扩展类
/// </summary>
public static class OpenHttpApiServiceCollectionExtensions
{
    /// <summary>
    /// 手动添加 httpapi 服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="config"></param>
    /// <returns></returns>
    public static IServiceCollection AddOpenHttpApi<THttpApi>(this IServiceCollection services)
        where THttpApi : class
    {
        var attribute = typeof(THttpApi).GetCustomAttribute<HttpApiOptionsAttribute>();
        if (attribute == null)
            throw new InvalidOperationException($"{typeof(THttpApi).Name}未定义{nameof(HttpApiOptions)}特性");
        //var options = new HttpApiOptions();
        //App.Configuration.GetSection(attribute.Path).Bind(options);
        var config = App.Configuration.GetSection(attribute.Path);
        services.AddHttpApi<THttpApi>()
            .ConfigureHttpApi(config)
            .ConfigureHttpApi(o =>
            {
                o.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
            });
        services.WebApiClientCoreRegister();
        return services;
    }

    /// <summary>
    /// 动态注册添加 httpapi 服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="config"></param>
    /// <returns></returns>
    public static IServiceCollection AddAllHttpApi(this IServiceCollection services)
    {
        var assemblies = DependencyContext.Default.RuntimeLibraries
                                            .Where(r => r.Type == "project" || r.Type == "package" && r.Name.Contains("ServiceAPI"))
                                            .Select(r => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(r.Name)))
                                            .ToHashSet();
        var httpApis = assemblies.SelectMany(assembly => assembly.GetTypes().Where(type => type.GetInterfaces().Contains(typeof(IHttpApi)) 
                                                                                && type.GetCustomAttribute<HttpApiOptionsAttribute>() != null));
        foreach (var httpApiType in httpApis)
        {
            var attribute = httpApiType.GetCustomAttribute<HttpApiOptionsAttribute>();
            if (attribute == null)
                continue;
            var config = App.Configuration.GetSection(attribute.Path);
            services.AddHttpApi(httpApiType)
                .ConfigureHttpApi(config)
                .ConfigureHttpApi(o =>
                {
                    o.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
                });
        }
        services.WebApiClientCoreRegister();
        return services;
    }

    /// <summary>
    /// IOC注册
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection WebApiClientCoreRegister(this IServiceCollection services)
    {
        services.AddScoped<HostProvider>();
        return services;
    }
}